package com.iflytek.demo;

import com.iflytek.demo.slice.MainAbilitySlice;
import com.iflytek.demo.ability.AppLog;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.bundle.IBundleManager;

public class MainAbility extends Ability {

    private static final int REQUEST_MICROPHONE = 10;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());
        requestPermission();
    }

    private void requestPermission() {
        if (verifySelfPermission("ohos.permission.MICROPHONE") != IBundleManager.PERMISSION_GRANTED) {
            // 应用未被授予权限
            if (canRequestPermission("ohos.permission.MICROPHONE")) {
                // 是否可以申请弹框授权(首次申请或者用户未选择禁止且不再提示)
                requestPermissionsFromUser(new String[]{"ohos.permission.MICROPHONE"}, REQUEST_MICROPHONE);
            } else {
                // 显示应用需要权限的理由，提示用户进入设置授权
            }
        } else {
            // 权限已被授予
        }
    }


    /**
     * 权限回调
     */
    @Override
    public void onRequestPermissionsFromUserResult(int requestCode,
                                                   String[] permissions,
                                                   int[] grantResults) {
        switch (requestCode) {
            case REQUEST_MICROPHONE: {
                // 匹配requestPermissions的requestCode
                if (grantResults.length > 0 && grantResults[0] == IBundleManager.PERMISSION_GRANTED) {
                    // 权限被授予
                    // 注意：因时间差导致接口权限检查时有无权限，所以对那些因无权限而抛异常的接口进行异常捕获处理
                    AppLog.e("MainAbility", "已经获取到录音权限");
                } else {
                    // 权限被拒绝
                    AppLog.e("MainAbility", "录音权限被拒绝");
                }
            }
        }
    }
}